/*
 * @Author: szx
 * @Date: 2022-03-13 10:43:34
 * @LastEditTime: 2022-03-13 12:13:42
 * @Description:
 * @FilePath: \leetcode\5200-5299\5227\5227.js
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var maximumTop = function (nums, k) {
    const n = nums.length;
    if (k == 0) return nums[0];
    if (k == 1) {
        if (n == 1) return -1;
        else return nums[1];
    }
    let top = 0;
    let max = -1;
    let cnt = 0;
    while (top < n - 1) {
        max = Math.max(nums[top++], max);
        cnt++;
        if (top == n - 1) {
            // console.log(top, cnt);
            if (k - cnt <= 1) return max;
            else {
                return Math.max(max, nums[top]);
            }
        }
        if (cnt == k - 1) {
            if (top < n - 1) {
                // console.log(nums[top]);
                return Math.max(max, nums[top + 1]);
            }
        }
    }
    return max;
};

var maximumTop = function (nums, k) {
    const n = nums.length;
    if (k == 0) return nums[0];
    if (n == 1)
        if (k & 1) return -1;
        else return nums[0];
    let max = -1;
    for (let x of nums) max = Math.max(max, x);
    if (k > n) return max;
    max = -1;
    for (let i = 0; i < k - 1; i++) {
        max = Math.max(max, nums[i]);
    }
    if (k < n) max = Math.max(max, nums[k]);
    return max;
};
console.log(maximumTop([3, 2, 1, 4], 4));

// console.log(maximumTop([5, 2, 2, 4, 0, 6], 4));
// console.log(maximumTop([5, 2, 2, 4, 7, 8], 9));
// console.log(maximumTop([2], 1));
// console.log(
//     maximumTop(
//         [
//             35, 43, 23, 86, 23, 45, 84, 2, 18, 83, 79, 28, 54, 81, 12, 94, 14, 0, 0, 29, 94, 12, 13, 1, 48, 85, 22, 95, 24, 5, 73, 10, 96, 97, 72, 41, 52, 1, 91, 3, 20, 22, 41, 98, 70, 20, 52, 48, 91,
//             84, 16, 30, 27, 35, 69, 33, 67, 18, 4, 53, 86, 78, 26, 83, 13, 96, 29, 15, 34, 80, 16, 49
//         ],
//         15
//     )
// );
// console.log(maximumTop([68, 76, 53, 73, 85, 87, 58, 24, 48, 59, 38, 80, 38, 65, 90, 38, 45, 22, 3, 28, 11], 1));
// console.log(maximumTop([3, 2, 1], 1));
